<template>
    <div class="cntr">
        <el-form
            ref="formRef"
            :model="formData"
            :rules="rules"
            label-width="100px"
            :size="'default'"
            status-icon
        >
            <el-row :gutter="2">
                <el-col :span="4">
                    <el-form-item label="箱号" prop="cntr">
                        <!-- <el-input v-model.trim="formData.cntr"/> -->
                        <textupperinput :disabled="true"
                            v-model.trim="formData.cntr"
                        ></textupperinput>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <!-- <el-form-item label="空重" prop="e_f_id">
                        <el-select v-model="formData.e_f_id" :clearable="true">
                            <el-option
                                v-for="optValue in SelectOptionEF"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </el-form-item> -->
                    <el-form-item label="进场箱况" prop="in_dam_id">
                        <el-select
                            v-model="formData.in_dam_id"
                            :clearable="true"
                        >
                            <el-option
                                v-for="optValue in cntrDam"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="箱况" prop="dam_id">
                        <el-select v-model="formData.dam_id" :clearable="true">
                            <el-option
                                v-for="optValue in cntrDam"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="尺寸" prop="cntr_siz_cod">
                        <el-select
                            v-model="formData.cntr_siz_cod"
                            :clearable="true"
                            disabled
                        >
                            <el-option
                                v-for="optValue in cntrSiz"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="箱型" prop="cntr_typ_cod">
                        <el-select
                            v-model="formData.cntr_typ_cod"
                            :clearable="true"
                            disabled
                        >
                            <el-option
                                v-for="optValue in cntrTyp"
                                :key="optValue.value"
                                :label="optValue.value"
                                :value="optValue.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="站点" prop="cfs_cod">
                        <el-select
                            v-model="formData.cfs_cod"
                            :clearable="true"
                            filterable
                            placeholder="Select"
                            disabled
                        >
                            <el-option
                                v-for="optValue in cyCfs"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="2">
                <el-col :span="4">
                    <el-form-item label="进场船名" prop="in_ship_nam">
                        <el-input v-model.trim="formData.in_ship_nam" />
                    </el-form-item>
                    <!-- <el-form-item label="供应商" prop="cntr_oper_cod">
                        <el-select
                            v-model="formData.cntr_oper_cod"
                            :clearable="true"
                            filterable
                            placeholder="Select"
                        >
                            <el-option
                                v-for="optValue in cntrOper"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </el-form-item> -->
                </el-col>
                <el-col :span="4">
                    <el-form-item label="进场航次" prop="in_voyage">
                        <el-input v-model.trim="formData.in_voyage" />
                    </el-form-item>
                    <!-- <el-form-item label="来箱地点" prop="from_plac">
                        <el-select
                            v-model="formData.from_plac"
                            :clearable="true"
                            filterable
                        placeholder="Select"
                        >
                            <el-option
                                v-for="optValue in place"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </el-form-item> -->
                </el-col>
                <el-col :span="4">
                    <el-form-item label="收箱提单号" prop="bill_no">
                        <!-- <el-input v-model.trim="formData.bill_no" /> -->
                        <textupperinput :disabled="true"
                            v-model.trim="formData.bill_no"
                        ></textupperinput>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="箱皮重" prop="cntr_new_wgt">
                        <el-input-number v-model="formData.cntr_new_wgt" />
                    </el-form-item>

                    <!-- <el-form-item label="箱贸易性质" prop="trade_id">
                        <el-select
                            v-model="formData.trade_id"
                            :clearable="true"
                        >
                            <el-option
                                v-for="optValue in SelectOptionTrade"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </el-form-item> -->
                </el-col>
                <el-col :span="4">
                    <el-form-item label="箱载重" prop="scale_wgt">
                        <el-input-number v-model="formData.scale_wgt" />
                    </el-form-item>
                </el-col>

                <!-- <el-col :span="4">
                    <el-form-item label="免堆期" prop="free_days">
                        <el-input-number v-model="formData.free_days" />
                    </el-form-item>
                </el-col> -->
            </el-row>
            <el-row :gutter="2">
                <el-col :span="4">
                    <el-form-item label="进场日期" prop="to_port_tim">
                        <el-date-picker
                            v-model="formData.to_port_tim"
                            type="datetime"
                            :size="'default'"
                            disabled
                        />
                    </el-form-item>
                </el-col>

                <el-col :span="4">
                    <el-form-item label="箱制造日期" prop="cntr_date">
                        <el-date-picker
                            v-model="formData.cntr_date"
                            type="date"
                            :size="'default'"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="机组品牌" prop="refmachine_brand">
                        <el-input v-model.trim="formData.refmachine_brand" />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="机组型号" prop="refmachine_model">
                        <el-input v-model.trim="formData.refmachine_model" />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="机组日期" prop="refmachine_date">
                        <el-date-picker
                            v-model="formData.refmachine_date"
                            type="date"
                            :size="'default'"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="箱主" prop="cntr_owner">
                        <el-select
                            v-model="formData.cntr_owner"
                            :clearable="true"
                            filterable
                            placeholder="Select"
                            disabled
                        >
                            <el-option
                                v-for="optValue in cntrOwner"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col>
                    <el-form-item label="备注" prop="remark">
                        <el-input v-model="formData.remark" />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </div>
    <div class="fee">
        <el-table
            ref="tableRef"
            :data="tableData"
            row-key="id"
            table-layout="auto"
            @row-dblclick="onFeeDbClick"
        >
            <template #empty>
                <span>无数据</span>
            </template>
            <el-table-column
                v-bind:align="'center'"
                prop="fee_unit_cod"
                label="客户"
                width="180"
            >
                <template #default="scope">
                    <template v-if="scope.row.isEdit">
                        <el-select
                            v-model="scope.row.fee_unit_cod"
                            
                        >
                            <el-option
                                v-for="optValue in client"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </template>
                    <template v-else>
                        {{ transFormatter(scope.row.fee_unit_cod, client) }}
                    </template>
                </template>
            </el-table-column>
            <el-table-column
                v-bind:align="'center'"
                prop="fee_in_out"
                label="收付"
                width="180"
            >
                <template #default="scope">
                    <template v-if="scope.row.isEdit">
                        <el-select
                            v-model="scope.row.fee_in_out"
                            
                        >
                            <el-option
                                v-for="optValue in SelectOptionFeeInOut"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </template>
                    <template v-else>
                        {{
                            transFormatter(
                                scope.row.fee_in_out,
                                SelectOptionFeeInOut,
                            )
                        }}
                    </template>
                </template>
            </el-table-column>
            <el-table-column
                v-bind:align="'center'"
                prop="fee_owner"
                label="成本中心"
                width="180"
            >
                <template #default="scope">
                    <template v-if="scope.row.isEdit">
                        <el-select
                            v-model="scope.row.fee_owner"
                        >
                            <el-option
                                v-for="optValue in cntrOwner"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </template>
                    <template v-else>
                        {{ transFormatter(scope.row.fee_owner, cntrOwner) }}
                    </template>
                </template>
            </el-table-column>
            
            <!-- <el-table-column
                v-bind:align="'center'"
                prop="fee_typ_cod"
                label="费用类型"
                width="180"
            >
                <template #default="scope">
                    <template v-if="scope.row.isEdit">
                        <el-select
                            v-model="scope.row.fee_typ_cod"
                        >
                            <el-option
                                v-for="optValue in feetyp"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </template>
                    <template v-else>
                        {{ transFormatter(scope.row.fee_typ_cod, feetyp) }}
                    </template>
                </template>
            </el-table-column>            
            <el-table-column
                v-bind:align="'center'"
                prop="fee_cod"
                label="费目"
                width="180"
            >
                <template #default="scope">
                    <template v-if="scope.row.isEdit">
                        <el-select
                            v-model="scope.row.fee_cod"
                            
                        >
                            <el-option
                                v-for="optValue in feecod"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </template>
                    <template v-else>
                        {{ transFormatter(scope.row.fee_cod, feecod) }}
                    </template>
                </template>
            </el-table-column> -->
            <el-table-column
                v-bind:align="'center'"
                prop="currency_cod"
                label="货币"
                width="180"
            >
                <template #default="scope">
                    <template v-if="scope.row.isEdit">
                        <el-select
                            v-model="scope.row.currency_cod"
                        >
                            <el-option
                                v-for="optValue in currency"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </template>
                    <template v-else>
                        {{ transFormatter(scope.row.currency_cod, currency) }}
                    </template>
                </template>
            </el-table-column>
            <!-- <el-table-column
                v-bind:align="'center'"
                prop="fee_value"
                label="单价"
                width="180"
            >
                <template #default="scope">
                    <template v-if="scope.row.isEdit">
                        <el-input-number
                            v-model="scope.row.fee_amount"
                        ></el-input-number>
                    </template>
                    <template v-else>
                        {{ scope.row.fee_amount }}
                    </template>
                </template>
            </el-table-column>
            <el-table-column
                v-bind:align="'center'"
                prop="fee_ton"
                label="数量"
                width="180"
            >
                <template #default="scope">
                    <template v-if="scope.row.isEdit">
                        <el-input-number
                            v-model="scope.row.fee_ton"
                        ></el-input-number>
                    </template>
                    <template v-else>
                        {{ scope.row.fee_ton }}
                    </template>
                </template>
            </el-table-column> -->
            <el-table-column
                v-bind:align="'center'"
                prop="amount"
                label="金额"
                width="180"
            >
                <template #default="scope">
                    <template v-if="scope.row.isEdit">
                        <el-input-number
                            v-model="scope.row.amount"
                            :min="0"
                        ></el-input-number>
                    </template>
                    <template v-else>
                        {{ scope.row.amount }}
                    </template>
                </template>
            </el-table-column>
            <el-table-column>
                <template #default="scope">
                    <template v-if="scope.row.isEdit">
                        <el-button
                            size="small"
                            type="primary"
                            @click="onEdit(scope.$index, scope.row)"
                            >确定</el-button
                        >
                        <el-button
                            size="small"
                            type="info"
                            @click="onCancel(scope.$index, scope.row)"
                            >取消</el-button
                        >
                        <el-button
                            size="small"
                            type="warning"
                            @click="onDel(scope.$index, scope.row)"
                            >删除</el-button
                        >
                    </template>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <div class="btn-group">
        <el-button-group>
            <el-button
                class="btn"
                type="primary"
                v-debounce="save"
                size="large"
            >
                保存
            </el-button>
            <el-button class="btn" type="primary" @click="reset" size="large"
                >重置</el-button
            >
            <!-- <el-button
                class="btn"
                type="primary"
                @click="addDefaultFee"
                size="large"
                >生成默认费用</el-button
            > -->
            <el-button class="btn" type="primary" @click="addFee" size="large"
                >增加费用</el-button
            >
            <template v-if="data">
                <el-button
                    class="btn"
                    type="primary"
                    @click="refreshFee"
                    size="large"
                    >显示费用</el-button
                >
            </template>
        </el-button-group>
    </div>
</template>
<script setup lang="ts" name="Cntr">
import { ref, reactive, onMounted, toValue } from 'vue';
import { storeToRefs } from 'pinia';
import {
    ElMessage,
    type FormInstance,
    type FormRules,
    type TableRefs,
} from 'element-plus';
import type { CntrModel } from '@/common/types/container';
import type { FeedetModel } from '@/common/types/business';
import { Request } from '@/app/request';
import { useAppStore } from '@/store/app';
import { useSysStore } from '@/store/sys';
import { transFormatter, validateCntr } from '@/common/tools';
import { isEmpty, isNil, omit, template } from 'lodash';
import { ValidateFieldsError } from 'async-validator';
import textupperinput from '@/components/forms/TextUpperInput.vue';

const {
    client, SelectOptionFeeInOut, feecod, currency,
    cntrDam,
    cntrSiz,
    cntrTyp,
    cyCfs,
    cntrOwner,
} = storeToRefs(useAppStore());
const { oper } = useSysStore();
const formRef = ref<FormInstance>();
const formData = reactive<CntrModel>({});
const tableRef = ref<TableRefs>();
const tableData = reactive<FeedetModel[]>([]);
const props = defineProps<{
    data: CntrModel;
}>();
const cascaderprops = {
  // checkStrictly: false,
  expandTrigger: 'hover' as const,
};
const emit = defineEmits<{
    update: [action: CntrModel];
    close: [];
}>();
const rules = reactive<FormRules>({
    cntr: [
        { required: true, message: '请输入箱号', trigger: 'blur' },
        { validator: validateCntr, trigger: 'blur' },
    ],

    dam_id: [{ required: true, message: '请输入好坏', trigger: 'blur' }],
    cntr_siz_cod: [{ required: true, message: '请输入尺寸', trigger: 'blur' }],
    cntr_typ_cod: [{ required: true, message: '请输入箱型', trigger: 'blur' }],
    cfs_cod: [{ required: true, message: '请输入站点', trigger: 'blur' }],
    to_port_tim: [
        { required: true, message: '请输入进场时间', trigger: 'blur' },
    ],
    bill_no: [{ required: true, message: '请输入收箱提单号', trigger: 'blur' }],
    /* cntr_owner: [{ required: true, message: '请输入箱主', trigger: 'blur' }], */
});
let temFeedet: any;

const reset = () => {
    formRef.value?.resetFields();
    // formData.trade_id = '1'; // 外贸
    // formData.e_f_id = 'E';
    formData.dam_id = 'AV';
    formData.in_dam_id = 'AV';
    // formData.in_truck_no_c = '鲁B';
    tableData.length = 0;
};

const refreshFee = async () => {
    const req = new Request('费用查询', {
        select: [
            'id',
            'fee_in_out',
            'fee_unit_cod',
            'fee_owner',
            'fee_typ_cod',
            'fee_cod',
            'amount',
            'currency_cod',
        ],
        where: {
            cntr_no: {
                equals: formData.id,
            },
        },
    });
    const r = await req.post();
    tableData.length = 0;

    if (!isEmpty(r.obj)) {
        for (let index = 0; index < r.obj.length; index++) {
            const element = r.obj[index];
            tableData.push(element);
        }
    }
};

onMounted(() => {
    reset();
    if (props.data) {
        //修改
        Object.assign(formData, props.data);
        // refreshFee();
    }
});
const save = async () => {
    const formValid = await formRef.value?.validate(
        (isValid: boolean, _invalidFields?: ValidateFieldsError) => {
            // return isValid;
            return;
        },
    );

    if (formValid) {
        for (let index = 0; index < tableData.length; index++) {
            tableData[index].cascaderfeecod = undefined;
            const element = tableData[index];
            if (element.amount! <= 0) {
                ElMessage({
                    type: 'info',
                    dangerouslyUseHTMLString: true,
                    message: '费用金额不能为0，不能保存',
                });
                return;
            }
            if (element.isEdit) {
                ElMessage({
                    type: 'info',
                    dangerouslyUseHTMLString: true,
                    message: '存在未保存费用',
                });
                return;
            }
        }
        if (props.data) {
            // 修改
            const param = toValue(formData);
            // param['feedet'] = toValue(tableData);
            const req = new Request('箱修改', param);
            const r = await req.post();
            if (r.code > 100) {
                emit('update', r.obj as CntrModel);
                // reset();
                return true;
            }
        } else {
            // 单箱进场
            const param = omit(formData, ['id']);
            param['feedet'] = toValue(tableData);
            const req = new Request('箱进场', param);
            const r = await req.post();
            if (r.code > 100) {
                // emit('create', r.obj as CntrModel);
                reset();
                return true;
            }
        }
    } else {
        return false;
    }
};
const addDefaultFee = () => {
    if (isNil(formData.cntr_oper_cod)) {
        ElMessage({
            type: 'info',
            dangerouslyUseHTMLString: true,
            message: '请输入供应商信息',
        });
        return;
    }
    tableData.forEach((element) => {
        if (element.fee_cod === '0101') {
            // 购箱费
            ElMessage({
                type: 'info',
                dangerouslyUseHTMLString: true,
                message: '已存在购箱费',
            });
            return;
        }
    });
    tableData.push({
        fee_unit_cod: formData.cntr_oper_cod,
        fee_in_out: 'O',
        fee_cod: '0101',
        currency_cod: 'RMB',
        amount: 0,
    });
};
const addFee = () => {
    tableData.push({
        isEdit: true,
        currency_cod: 'RMB',
    });
    temFeedet = null;
};
//费用删除
const onDel = async (index: number, row: any) => {
    if (props.data) {
        const req = new Request('费用删除', { ids: [row.id] });
        const r = await req.post();
        if (r.code > 100) {
            tableData.splice(index, 1);
        }
    } else {
        tableData.splice(index, 1);
    }
};
//费用表双击
const onFeeDbClick = (row: any) => {
    // console.log(row);
    if (row.isEdit) {
        return;
    }
    temFeedet = {};
    row.cascaderfeecod = [];
    if (row.fee_typ_cod) {
        row.cascaderfeecod[0] = row.fee_typ_cod;
    }
    if (row.fee_cod) {
        row.cascaderfeecod[1] = row.fee_cod;
    }
    Object.assign(temFeedet, omit(row, ['isEdit']));
    row.isEdit = true;
};
// 费用确定
const onEdit = async (index: number, row: FeedetModel) => {
    if (row.cascaderfeecod) {
        row.fee_typ_cod = row.cascaderfeecod[0];
        row.fee_cod = row.cascaderfeecod[1];
    } else {
        row.fee_typ_cod = undefined;
        row.fee_cod = undefined;
    }
    row.cascaderfeecod = undefined;    
    row.isEdit = false;
    if (props.data) {
        if (row.id) {
            const req = new Request('费用修改', omit(row, ['isEdit']));
            const r = await req.post();
        } else {
            row['cntr_no'] = formData.id;
            row['fee_nam'] = oper.name;
            row['fee_tim'] = formData.to_port_tim;
            const req = new Request('费用增加', omit(row, ['isEdit']));
            const r = await req.post();
        }
    }
};
// 费用取消修改
const onCancel = (index: number, row: FeedetModel) => {
    if (isNil(temFeedet)) {
        tableData.splice(index, 1);
    } else {
        Object.assign(row, temFeedet);
        row.cascaderfeecod = undefined;
        row.isEdit = false;
    }
};
</script>
<style lang="scss" scoped>
.cntr {
    margin-bottom: 20px;
    padding: 10px 10px;
    border: solid 2px var(--el-color-primary);
    box-shadow: 10px 10px 5px rgba(100, 100, 100, 0.5);
}
.fee {
    margin-bottom: 20px;
    padding-top: 10px 10px;
    border: solid 2px var(--el-color-primary);
    box-shadow: 10px 10px 5px rgba(100, 100, 100, 0.5);
}
.btn-group {
    .btn {
        margin-right: 5px;
    }
}
</style>
